//
//  RadioDetailInfoViewController.m
//  Cup
//
//  Created by dllo on 15/4/23.
//  Copyright (c) 2015年 doll. All rights reserved.
//

#import "RadioDetailInfoViewController.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import "UMSocial.h"
#import "ShareView.h"
#import "OtherPlaying.h"
#import "dataBaseHandle.h"
#import "PlayInfo.h"
#import "MyRadioInfoCell.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface RadioDetailInfoViewController ()<UIWebViewDelegate,UMSocialUIDelegate>
@property(nonatomic,retain)NSDictionary *playInfo;
@property(nonatomic,retain)UIImageView *coverIMG;
@property(nonatomic,retain)UILabel *name;
@property(nonatomic,retain)UIButton *mediaButton;
@property(nonatomic,assign)BOOL isSelected;
@property(nonatomic,retain)UIWebView *webView;
@property(nonatomic,retain)ShareView *shareView;
@property(nonatomic,assign)BOOL isShow;
@property(nonatomic,copy)NSString *playURL;
@property(nonatomic,retain)PlayInfo *PlayMo;
@property(nonatomic, assign)NSInteger num;
@property(nonatomic,retain)UITableView *tableView;
@property(nonatomic,copy)NSString *webviewHeight;
@property(nonatomic,retain)NSURL *webURL;
@end
@implementation RadioDetailInfoViewController
- (void)dealloc
{
    _webView.delegate = nil;
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
//    [_playInfo release];
    [_coverIMG release];
    [_name release];
//    [_mediaButton release];
    [_webView release];
    [_shareView release];
    [_playInfo release];
    [_PlayMo release];
    [super dealloc];
}

- (void)detailInfoData
{
    if ([dataBaseHandle shareDB].state == 1) {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSDictionary *dic = @{@"client":@"1",@"deviceid":@"C6972C4A-C6C9-44C4-B88D-C33304867ED8",@"tingid":self.tingid,@"auth":@"XsU9RSm3j9KNDCMV0HcPulzJxQ8evMuXf9TpuCjI2cWP23tdMTx9a6vo",@"version":@"3.0.1"};
        [manager POST:@"http://api2.pianke.me/ting/info" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *data = [responseObject objectForKey:@"data"];
            self.title = [data objectForKey:@"radioname"];
            self.playInfo = [data objectForKey:@"playInfo"];
            NSURL *coverIMGURL = [NSURL URLWithString:[self.playInfo objectForKey:@"imgUrl"]];
            [self.coverIMG sd_setImageWithURL:coverIMGURL];
            self.name.text = [self.playInfo objectForKey:@"title"];
            self.playURL = [self.playInfo objectForKey:@"musicUrl"];
            self.webURL = [NSURL URLWithString:self.playInfo[@"webview_url"]];
            NSURLRequest *request = [NSURLRequest requestWithURL:self.webURL];
            [self.webView loadRequest:request];
            [self.webView sizeToFit];
            self.PlayMo = [[PlayInfo alloc] init];
            [self.PlayMo setValuesForKeysWithDictionary:self.playInfo];
            [self.tableView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
        }];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前无网络，请检查网络后重新尝试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

- (void)viewDidLoad {
    self.view.backgroundColor = [UIColor whiteColor];
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 360)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    self.coverIMG = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0,WIDTH, 280)];
    [self.tableView.tableHeaderView addSubview:self.coverIMG];
    [_coverIMG release];

    self.name = [[UILabel alloc]initWithFrame:CGRectMake(0, 290, WIDTH, 30)];
    self.name.textAlignment = NSTextAlignmentCenter;
    [self.tableView.tableHeaderView addSubview:self.name];
    [_name release];

    self.isSelected = NO;
    self.mediaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.mediaButton.frame = CGRectMake(WIDTH/2 - 20, 320, 40, 40);
    [self.mediaButton setImage:[UIImage imageNamed:@"MediaStop.png"] forState:UIControlStateNormal];
    [self.tableView.tableHeaderView addSubview:self.mediaButton];
    [self.mediaButton addTarget:self action:@selector(playState) forControlEvents:UIControlEventTouchUpInside];

    self.webView = [[UIWebView alloc]init];
    self.webView.delegate = self;
    self.webView.scalesPageToFit = YES;

    self.shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 70)];
    self.shareView.backgroundColor =  [UIColor colorWithRed:207/255.0 green:133/255.0 blue:128/255.0 alpha:1];
    [self.view addSubview:self.shareView];
    [self.shareView.share addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.shareView.collect addTarget:self action:@selector(collect) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-xia.png"] style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:59/255.0 green:54/255.0 blue:24/255.0 alpha:1];
    self.isShow = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(turnBack)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:59/255.0 green:54/255.0 blue:24/255.0 alpha:1];
    [self detailInfoData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse";
    MyRadioInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (cell == nil) {
        cell = [[MyRadioInfoCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
    }
    self.tableView.rowHeight = [self.webviewHeight floatValue];
    NSLog(@"%g",self.tableView.rowHeight);
    [cell.myView addSubview:self.webView];
    UIScrollView *tempView = (UIScrollView *)[self.webView.subviews objectAtIndex:0];
    tempView.scrollEnabled = NO;
    tempView.contentSize = CGSizeMake(self.webView.frame.size.width, [self.webviewHeight floatValue]+1);
    return cell;
}

- (void)turnBack
{
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickRightButton
{
    if (self.isShow == NO) {
        [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"iconfont-shang"]];
        self.isShow = YES;
        self.shareView.hidden = NO;
    }else{
        [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"iconfont-xia"]];
        self.isShow = NO;
        self.shareView.hidden = YES;
    }
}

- (void)share
{
    NSString *str = [self.playInfo objectForKey:@"sharepic"];
    UIImage *shareImage = [UIImage imageNamed:str];
    NSString *shareText = [self.playInfo objectForKey:@"sharetext"];
    NSString *shareURL = [self.playInfo objectForKey:@"shareurl"];
    NSString *share = [NSString stringWithFormat:@"%@ %@",shareText,shareURL];

    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"553afad967e58e7cba0031e4" shareText:share  shareImage:shareImage shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQQ, nil] delegate:self];
}

// 收藏部分
- (void)collect
{
    [[dataBaseHandle shareDB] openDB];
    [[dataBaseHandle shareDB] creatPlayerTable];
    NSMutableArray *arr = [[dataBaseHandle shareDB] selectPlayer];
    if (arr.count > 0) {
        for (PlayInfo *playmo in arr) {
            if ([playmo.title isEqual:self.PlayMo.title]) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                self.num = 1;
                [alert show];
                [alert release];
                break;
                }
        }
        if (self.num != 1) {
            [[dataBaseHandle shareDB] insertPlayerWithTitle:self.PlayMo.title imgUrl:self.PlayMo.imgUrl musicid:self.tingid];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
    if (arr.count == 0) {
        [[dataBaseHandle shareDB] insertPlayerWithTitle:self.PlayMo.title imgUrl:self.PlayMo.imgUrl musicid:self.tingid];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

// 获得webView的高度
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    self.webviewHeight = [self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] ;

    CGFloat height = [self.webviewHeight floatValue];
    self.webView.frame = CGRectMake(0, 0, self.view.frame.size.width, height);
    [self.tableView reloadData];
}

// 中断的时候暂停
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player NS_DEPRECATED_IOS(2_2, 8_0)
{
   [[OtherPlaying shareOtherPlaying].player pause];
}

// 继续播放
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags NS_DEPRECATED_IOS(6_0, 8_0)
{
    [[OtherPlaying shareOtherPlaying].player play];
}

- (void)playState
{
    if (self.isSelected == NO) {
        [self.mediaButton setImage:[UIImage imageNamed:@"MediaPlaye.png"] forState:UIControlStateNormal];
        if (![[OtherPlaying shareOtherPlaying].currentURL isEqualToString:self.playURL]) {
            [[OtherPlaying shareOtherPlaying]createPlay:[NSURL URLWithString:self.playURL]];
        }
        [[OtherPlaying shareOtherPlaying].player play];
    }
    else{
        [self.mediaButton setImage:[UIImage imageNamed:@"MediaStop.png"] forState:UIControlStateNormal];
        [[OtherPlaying shareOtherPlaying].player pause];
    }
    self.isSelected = !self.isSelected;
}

// 歌曲播放完毕
- (void)PlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self.mediaButton setImage:[UIImage imageNamed:@"MediaStop.png"] forState:UIControlStateNormal];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
